package com.xnyzc.lhy.common.component.sms;

import com.submail.config.AppConfig;
import com.submail.lib.MessageMultiSend;
import com.submail.utils.ConfigLoader;
import com.xnyzc.lhy.common.constant.SmsConstant;
import com.xnyzc.lhy.common.entity.sms.SubMailResult;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>SubMail 短信发送</p>
 *
 * @author liuju
 * @version v1.0
 * @since 2015/5/5
 */
@Slf4j
@Component
public class SubMailUtil {

    private static String smsAppId;

    private static String smsAppKey;

    private static String smsSignature;

    private static String smsSignType="md5";

    @Value("${global.subMail.appId}")
    public void setSmsAppId(String appId) {
        smsAppId = appId;
    }

    @Value("${global.subMail.appKey}")
    public void setSmsAppKey(String appKey) {
        smsAppKey = appKey;
    }

    @Value("${global.subMail.signature}")
    public void setSmsSignature(String signature) {
        smsSignature = signature;
    }


    /**
     * 单条短信发送
     *
     * @param phone
     * @param smsJson
     */
    public static void messageMultiSend(String phone, String content, JSONObject smsJson) {
        AppConfig config = ConfigLoader.createConfig(smsAppId, smsAppKey, smsSignType);
        MessageMultiSend subMail = new MessageMultiSend(config);
        subMail.addContent(smsSignature + content);
        subMail.addVars(smsJson);
        subMail.addMulti(phone);
        // 发送短信
        String result = null;
        try {
            result = subMail.multixsend();
        } catch (NoSuchAlgorithmException e) {
            log.error("{} 短信发送失败,内容:{}", phone, content);
            throw PangException.create(EErrorCode.smsSendError);
        } catch (IOException e) {
            log.error("{} 短信发送失败,内容:{}", phone, content);
            throw PangException.create(EErrorCode.smsSendError);
        }
        // 解析结果
        JSONArray resultJson = JSONArray.fromObject(result);
        if (!CheckUtil.objIsEmpty(resultJson)) {
            for (int i = 0; i < resultJson.size(); i++) {
                JSONObject jsonObject = resultJson.getJSONObject(i);
                if (!Objects.equals(jsonObject.getString("status"), SmsConstant.SUCCESS)) {
                    throw PangException.create(EErrorCode.smsSendError);
                }
            }
        } else {
            throw PangException.create(EErrorCode.smsSendError);
        }
    }

    /**
     * 批量短信发送
     *  @param phoneList
     * @param smsJson*/
    public static SubMailResult messageMultiSends(List<String> phoneList, String content, JSONObject smsJson) {
        AppConfig config = ConfigLoader.createConfig(smsAppId, smsAppKey, smsSignType);
        MessageMultiSend subMail = new MessageMultiSend(config);
        subMail.addContent(smsSignature + content);
        subMail.addVars(smsJson);
        if (CheckUtil.collectionIsEmpty(phoneList)) {
            throw new PangException(EErrorCode.missingArg);
        }
        for (String phone : phoneList) {
            subMail.addMulti(phone);
        }

        // 发送短信
        String result;
        try {
            result = subMail.multixsend();
        } catch (NoSuchAlgorithmException e) {
            log.error("短信发送失败,内容:{}", content);
            throw PangException.create(EErrorCode.smsSendError);
        } catch (IOException e) {
            log.error("短信发送失败,内容:{}", content);
            throw PangException.create(EErrorCode.smsSendError);
        }

        // 解析结果
        JSONArray resultJson = JSONArray.fromObject(result);

        List<String> phoneSuccessList=new ArrayList<>();
        if (!CheckUtil.objIsEmpty(resultJson)) {
            for (int i = 0; i < resultJson.size(); i++) {
                JSONObject jsonObject = resultJson.getJSONObject(i);
                if (Objects.equals(jsonObject.getString("status"), SmsConstant.SUCCESS)) {
                    phoneSuccessList.add(jsonObject.getString("to"));
                }
            }
        } else {
            throw PangException.create(EErrorCode.smsSendError);
        }

        // 筛选发送失败的手机号
        phoneList.removeAll(phoneSuccessList);

        SubMailResult subMailResult=new SubMailResult();
        if(CheckUtil.objIsEmpty(phoneList)){
            subMailResult.setStatus(true);
        }else{
            subMailResult.setStatus(false);
            subMailResult.setPhoneList(phoneList);
        }

        return subMailResult;
    }
}
